import NProgress from 'nprogress'
import getPageTitle from './getPageTitle'
import store from '@/store'
import whiteList from '@/components/storybook/settings/whiteList'
import { saveShareInfo } from '@/views/pages/login/login.data'
import { getToken } from './auth'
import Vue from 'vue'
import router, { asyncRoutes } from '@/components/storybook/router'
import { sqlSet } from '@/components/storybook/utilties/throttleRequest'
import { toLower, get, has } from 'lodash'
import { slackAppInstall } from '@/api/modules/notice'
const needFillRouteMeta = route => {
  if (
    route.name !== 'DashboardDetailLayout' &&
    route.name !== 'ReportDetailLayout' &&
    route.name !== 'ScorecardDetailLayout' &&
    route.name !== 'BotDetailLayout' &&
    route.name !== 'NextTicketPriorityRulesLayout' &&
    route.name !== 'UserFilterRuleLayout' &&
    route.name !== 'ClientWatchListLayout' &&
    route.name !== 'DatasetDetailLayout'
  )
    return false

  const afterId = get(route, 'params.afterId')
  if (afterId && !has(route, 'query.name')) {
    return afterId
  }

  return false
}

NProgress.configure({
  showSpinner: false
})

router.beforeEach(async (to, from, next) => {
  try {
    if(to.path === '/login') {
      if (to.query.type === 'slackappinstall') {
        slackAppInstall(to.query)
      }
    }
  } catch (error) {
    
  }
  const afterId = needFillRouteMeta(to)

  if (afterId) {
    const name = await store.dispatch('fillRouteMeta', afterId)
    to.query.name = name
    if(to.query.pageid){
      if(!to.query.layout){
        to.query.layout = 'report_layout'
      }
    }
  }

  NProgress.start()

  if (to.path === '/NPS') {
    next({
      path: '/userForm',
      query: {
        ...to.query,
        formCode: '1541637280530305024',
        autoSubmit: 'true'
      }
    })
  }

  if (
    !sessionStorage.getItem('isLoginRouterPath') &&
    to.fullPath !== '/login' &&
    to.fullPath !== '/loginAsAccount'
  ) {
    sessionStorage.setItem('isLoginRouterPath', to.fullPath)
  }
  if (to.path === '/connectWiseManageAssets') {
    to.meta.title = to.query.name
  }

  document.title = getPageTitle(to)

  const hasToken = getToken()

  if (hasToken) {
    if (
      to.path === '/login' ||
      to.path === '/emaillogin' ||
      to.path === '/loginAsAccount'
    ) {
      setTimeout(() => {
        saveShareInfo(to.fullPath)
      }, 15000)
      next({
        path: '/'
      })
      NProgress.done()
    } else if (to.path === '/portal') {
      next()
    } else {
      const hasRoutes = store.getters.routes && store.getters.routes.length > 0

      if (hasRoutes) {
        next()
      } else {
        try {
          const accessRoutes = await store.dispatch('generateRoutes')
          Vue.prototype.$interface.other.getLoginConfigInfo({}).then(({data:res}) => {
            let tempHost = window.location.hostname
            if(tempHost && tempHost !== 'localhost' && res.data.length > 0) {         
              store.state.siteWebConfig = res.data.filter(e=>e.origin === tempHost)[0]          
            }
          })
          router.addRoutes([
            ...asyncRoutes(accessRoutes),
            {
              path: '*',
              redirect: '/404',
              hidden: true
            }
          ])
          store.commit('SET_API_LOAD_TEXT', 'Loading')
          store.commit('SET_API_LOAD_STATUS', false)
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          if (toLower(whiteList).indexOf(toLower(to.path)) !== -1) {
            next()
          } else {
            next({
              path: window.location.href.includes('portal')
                ? `/loginAsAccount`
                : store.state.system.loginRouter,
              query: {
                redirect: to.path,
                ...to.query
              }
            })
          }
          NProgress.done()
          store.commit('SET_API_LOAD_STATUS', false)
        }
        NProgress.done()
        store.commit('SET_API_LOAD_STATUS', false)
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next({
        path: window.location.href.includes('portal')
          ? `/loginAsAccount`
          : store.state.system.loginRouter,
        query: {
          redirect: to.path,
          ...to.query
        }
      })
    }
    NProgress.done()
    store.commit('SET_API_LOAD_STATUS', false)
  }
})

router.afterEach(to => {
  sqlSet.clear()
  const userName = store.state.user.username
  // const _hsq = (window._hsq = window._hsq || [])
  // const _paq = window._paq || []
  // _hsq.push(['setPath', to.path])
  // _hsq.push(['trackPageView'])
  // _paq.push(['trackPageView'])

  if (userName) {
    // _hsq.push([
    //   'identify',
    //   {
    //     email: userName
    //   }
    // ])
    // _paq.push(['setUserId', userName])
    const temp = store.state.app.isSwitchTenant
      ? store.state.app.isSwitchTenant
      : sessionStorage.getItem('isSwitchTenant')
    const params = {
      url: to.fullPath.includes('&appResourceList')
        ? to.fullPath.split('&appResourceList')[0]
        : to.fullPath,
      loginAs: temp || 0
    }
    if (
      to.path !== '/portal' &&
      to.path !== '/code' &&
      to.path !== '/2fa' &&
      to.path !== '/emaillogin'
    ) {
      Vue.prototype.$interface.um.poststatRouteAPI(params)
    }
  }

  NProgress.done()
})

export default router
